package cn.fl.project.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.ass.vo.AssDealSellLossVO;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.customer.service.ICstCorpTeamService;
import cn.fl.customer.vo.CstBscInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.condition.PrjLinkManQueryCondition;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.service.IPrjLinkManService;
import cn.fl.project.vo.PrjLinkManVO;
import cn.fl.system.constant.SysLogConstant;
import fl.customer.facade.customer.constant.CustomerConstant;
import net.sf.json.JSONArray;

/**
 * @Description: 项目联系人信息表 控制层
 */
@Controller
@RequestMapping("/project/prjlinkman")
public class PrjLinkManController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(PrjLinkManController.class);


	/**
	 * PrjLinkMan 服务层BEAN
	 */
	@Autowired
	private IPrjLinkManService prjLinkManService;

	/**
	 * PrjLinkMan 服务层BEAN
	 */
	@Autowired
	private ICstBscInfoService cstBscInfoService;
	@Autowired
	private IPrjBscInfoService prjBscInfoService;
	@Autowired
	private ICstCorpTeamService cstCorpTeamService;//法人企业团队信息表
	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		String prjId = request.getParameter("prjId");
		String detailFlag = request.getParameter("detailFlag");
		Long cstId = null;
		CstBscInfoVO cstBscInfoVO = null; 
		if(StringUtils.isNotBlank(prjId)){
			cstBscInfoVO = prjBscInfoService.getCstTypByPrjId(Long.valueOf(prjId));
			if(null!=cstBscInfoVO){
				 cstId= cstBscInfoVO.getId();
			}
		}

		ModelAndView view = new ModelAndView("project/prjlinkman/prjLinkManList");
		view.addObject("cstId", cstId);
		view.addObject("prjId", prjId);
		view.addObject("detailFlag", detailFlag);
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("project/prjLinkMan/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String prjId = request.getParameter("prjId");
		//String cstId = request.getParameter("cstId");
		prjId = prjBscInfoService.getPrjIdByPrjId(prjId);
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(currentPage)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		PrjLinkManQueryCondition qc = new PrjLinkManQueryCondition();
		if (StringUtils.isNotEmpty(prjId)) {
			qc.setPrjId(Long.valueOf(prjId));
		}
		//qc.setCstId(Long.valueOf(cstId));
		page.setCondition(qc);

		Pager pager = this.prjLinkManService.searchListPage(page);
		List<PrjLinkManVO> list = (List<PrjLinkManVO>) pager.getResultList();
		/*CstCorpTeamQueryCondition cond = new CstCorpTeamQueryCondition();
		cond.setCstId(Long.valueOf(cstId));
		cond.setSysCd(CurrentThreadContext.getCurrentSysCd());
		List<CstCorpTeamVO> teamList = 	cstCorpTeamService.searchList(cond);
		CstCorpTeamVO teamVo = null;
		ListPageVO<PrjLinkManVO> listPage = null;
		if(CollectionUtils.isEmpty(list)){
			if(null!=teamList){
				if(CollectionUtils.isNotEmpty(teamList)){
					for (CstCorpTeamVO team : teamList) {
						if(team.getMTypCd().equals(CustomerConstant.CST_Rl_ATTR_LNK)){
							//成员类型为联系人
							teamVo = team;//查找一个联系人
							break;
						}
					}
				}
			}
			list = new ArrayList<PrjLinkManVO>();
			if(null!=teamVo){
				//设置客户那边的联系人信息
				PrjLinkManVO link = new PrjLinkManVO();
				 link.setLnkTypCd(PrjBscInfoConstant.CODE_PRJ_LNK_TYP_MAIN);//主要联系人
				 link.setLnkTypCdNm(PrjBscInfoConstant.CODE_PRJ_LNK_TYP_MAIN_NM);
				 link.setCertTypCd(teamVo.getCertTypCd());
				 link.setCertTypCdNm(teamVo.getCertTypCdNm());
				 link.setCertNo(teamVo.getCertNo());
				 link.setLnkNm(teamVo.getMNm());
				 link.setHomeAddr(teamVo.getHomeAddr());
				 link.setIsDel(BaseConstant.IS_YESNO_NO);
				 link.setPrjId(Long.valueOf(prjId));
				 link.setCstId(Long.valueOf(cstId));
				 link.setMp(teamVo.getMp1());
				 list.add(link);
				 
				 
				//设置客户那边的联系人信息
					PrjLinkManVO sec = new PrjLinkManVO();
					sec.setLnkTypCd(PrjBscInfoConstant.CODE_PRJ_LNK_TYP_SEC);//主要联系人
					sec.setLnkTypCdNm(PrjBscInfoConstant.CODE_PRJ_LNK_TYP_SEC_NM);
					sec.setIsDel(BaseConstant.IS_YESNO_NO);
					sec.setPrjId(Long.valueOf(prjId));
					sec.setCstId(Long.valueOf(cstId));
					 list.add(sec);
				 listPage = new ListPageVO<PrjLinkManVO>(list, list.size());
			}else{
				//设置客户那边的联系人信息
				PrjLinkManVO mainLink = new PrjLinkManVO();
				mainLink.setLnkTypCd(PrjBscInfoConstant.CODE_PRJ_LNK_TYP_MAIN);//主要联系人
				mainLink.setLnkTypCdNm(PrjBscInfoConstant.CODE_PRJ_LNK_TYP_MAIN_NM);
				mainLink.setIsDel(BaseConstant.IS_YESNO_NO);
				mainLink.setPrjId(Long.valueOf(prjId));
				mainLink.setCstId(Long.valueOf(cstId));
				 list.add(mainLink);
				//设置客户那边的联系人信息
					PrjLinkManVO secLink = new PrjLinkManVO();
					secLink.setLnkTypCd(PrjBscInfoConstant.CODE_PRJ_LNK_TYP_SEC);//主要联系人
					secLink.setLnkTypCdNm(PrjBscInfoConstant.CODE_PRJ_LNK_TYP_SEC_NM);
					secLink.setIsDel(BaseConstant.IS_YESNO_NO);
					secLink.setPrjId(Long.valueOf(prjId));
					secLink.setCstId(Long.valueOf(cstId));
					list.add(secLink);
				 listPage = new ListPageVO<PrjLinkManVO>(list, list.size());
			}
		}else{
		}*/
		ListPageVO<PrjLinkManVO> 	listPage = new ListPageVO<PrjLinkManVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(ids)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		List<Long> idList = new ArrayList<Long>();
		JSONArray idsArray = JSONArray.fromObject(ids);
		for (Object object : idsArray) {
			idList.add(Long.valueOf(object.toString()));
		}
		try {
			this.prjLinkManService.removeByIds(idList);
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+ids+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+ids+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+ids+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		result.setSuccess(BaseConstant.IS_YESNO_YES);
		return result;
	}
	 /**
     * 删除-- 第三方联系人信息
     */
    @RequestMapping(value = "/delByLinkMans.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object delByLinkMans(HttpServletRequest request, HttpServletResponse response) throws BaseException {
       
	 	DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
	 	List<Long> idList = new ArrayList<Long>();
    	String data = request.getParameter("parms");
    	com.alibaba.fastjson.JSONArray array = JSON.parseArray(data);
    	for (Object object : array) {
    		JSONObject obj=	(JSONObject) object;
    		Long LinkManId=(Long) obj.get("id");//亏损id
    		idList.add(LinkManId);
			if(StringUtils.isEmpty(LinkManId)){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
					BaseLogUtils.info(logger, "delAssDealSellLoss", "删除数据,亏损业务主键不存在.[lossId="+LinkManId+"]", CurrentThreadContext.getCurrentUserName());
					return result;
			}
		
        try {
        	//entity.setIsDel(Long.valueOf("1"));
            BaseLogUtils.info(logger, "delAssDealSellLoss", "删除亏损信息表数据Start,ID:" + LinkManId + ".DATA:" + JSONObject.toJSONString(idList), CurrentThreadContext.getCurrentUserName());
            boolean removeByIds = this.prjLinkManService.removeByIds(idList);
            BaseLogUtils.info(logger, "delAssDealSellLoss", "删除亏损信息表数据End,删除亏损信息表数据成功,ID:" + LinkManId + ".DATA:" + JSONObject.toJSONString(idList), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "delAssDealSellLoss", "删除亏损信息表数据失败.DATA:" + JSONObject.toJSONString(idList), CurrentThreadContext.getCurrentUserName(), ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "delAssDealSellLoss", "删除亏损信息表数据失败,系统错误.DATA:" + JSONObject.toJSONString(idList), CurrentThreadContext.getCurrentUserName(), ex);
        }
    }
        return result;
    }
	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getDataList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getDataList(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		
		try {
			List<List<KeyValueVO>> list = new ArrayList<List<KeyValueVO>>();
			List<KeyValueVO> lnkTpyList = this.prjBscInfoService.getLnkTypCdList();//
			List<KeyValueVO>   gendList = this.cstBscInfoService.searchGenderCdList();
			List<KeyValueVO>   certTypeList  = this.cstBscInfoService.searchCertTypCdList(CustomerConstant.CST_TYP_CD_NP);
			list.add( lnkTpyList);
			list.add(gendList);
			list.add(certTypeList);
			result.setData(list);
			BaseLogUtils.info(logger, "getById", "获取数据.[list="+list+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			PrjLinkManVO vo = this.prjLinkManService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String prjlinkManList = request.getParameter("prjlinkManList");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		PrjLinkManVO entity = null;
		String prjId = request.getParameter("prjId");
		String cstId = request.getParameter("cstId");
		List<PrjLinkManVO> list = new ArrayList<PrjLinkManVO>();
		try {
		if (StringUtils.isNotBlank(prjlinkManList)) {
			list = JSON.parseArray(prjlinkManList, PrjLinkManVO.class);
			for(int i=0;i<list.size();i++){
				PrjLinkManVO link = list.get(i);
				if(StringUtils.isBlank(link.getLnkNm())&&
						StringUtils.isBlank(link.getLnkNm())&&
						StringUtils.isBlank(link.getGenderCd())&&
						StringUtils.isBlank(link.getCertNo())&&
						StringUtils.isBlank(link.getMp())&&
						StringUtils.isBlank(link.getRlCd())&&
						StringUtils.isBlank(link.getVisRec())){
					list.remove(i);
				}
			}
		}
		for (PrjLinkManVO link : list) {
			if(StringUtils.isNotBlank(prjId)){
				link.setPrjId(Long.valueOf(prjId));
			}
			if (StringUtils.isBlank(link.getLnkNm())){
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"姓名不能为空！");
			}
			/*if(StringUtils.isNotBlank(cstId)){
				link.setCstId(Long.valueOf(cstId));
			}*/
			
			/*if(StringUtils.isBlank(link.getGenderCd())){
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"性别不能为空！");
			}*/
			/*if(StringUtils.isBlank(link.getMp())){
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"手机号码不能为空！");
			}*/
			if(!StringUtils.checkMobileNumber(link.getMp())){
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"手机号码不正确！");
			}
			if(StringUtils.isBlank(link.getRlCd())){
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"与承租人关系不能为空！");
			}
		//	}
		/*	if(StringUtils.isBlank(link.getCertTypCd())){
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"证件类型不能为空！");
			}
			if(StringUtils.isBlank(link.getCertNo())){
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"证件号码不能为空！");
			}else{
				if(!StringUtils.isIdCardNumber(link.getCertNo())){
					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"证件号码不正确！");
				}
			}*/
		}
	
			 this.prjLinkManService.addPrjLinkManList(list);
			BaseLogUtils.info(logger, "add", "新增数据.[list="+list+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		PrjLinkManVO entity = null;
		try {
			entity = new PrjLinkManVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.prjLinkManService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
}

